﻿using AutoMapper;
using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Write.API.Command.RoleCommand;
using MediatR;

namespace B.S.BaseData.Write.API.CommandHandler.RoleHandler
{
    public class AddRoleHandler : IRequestHandler<AddRoleCommand, APIResult<object>>
    {
        private readonly IBaseRepository<Role> roleRep;
        private readonly IMapper mapper;

        public AddRoleHandler(IBaseRepository<Role> roleRep,IMapper mapper)
        {
            this.roleRep = roleRep;
            this.mapper = mapper;
        }
        public Task<APIResult<object>> Handle(AddRoleCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            var model=mapper.Map<Role>(request);
            var name = roleRep.GetAll().Where(x=>x.RoleName==request.RoleName);
            if (name.Count()>0)
            {
                result.Code = APIEnum.Failed;
                result.Msg = "有重名不能添加";
                result.Data = -1;
            }
            else
            {
                model.CreateUser = "admin";
                model.CreateTime = DateTime.Now;
                model.UpdateUser = "";
                model.IsDeleted = false;
                roleRep.Add(model);
                result.Code = APIEnum.Success;
                result.Msg = "添加成功";
                result.Data = 1;
            }
            return Task.FromResult(result);
        }
    }
}
